from sklearn.datasets import load_boston
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

boston = load_boston()
# 房价数据分割
x_train, x_test, y_train, y_test = train_test_split(boston.data,boston.target)

# 训练与测试数据标准化处理
ss = StandardScaler()
# 训练集特征值转换
x_train = ss.fit_transform(x_train)
# 测试集特征值转换
x_test = ss.transform(x_test)

# 解决回归问题，如果对特征值进行标准化，对目标值也需要
ss_y = StandardScaler()
# 对训练集的模板值的标准化，不能使用原来对特征值的StandardScaler
# Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.
y_train = ss_y.fit_transform(y_train.reshape(-1,1))

# lasso回归
lasso = Lasso(alpha=0.1)  # 通过调这个参数会得到不同的误差值
lasso.fit(x_train,y_train)
lasso_predict = lasso.predict(x_test)
lasso_error = mean_squared_error(y_true=y_test, y_pred=ss_y.inverse_transform(lasso_predict))
print(lasso_error)


# lassoCV回归
alphas=[0.01, 0.1, 0.5, 1, 3, 5, 7, 10, 20, 100]
lasso = LassoCV(alphas=alphas)  # 通过调这个参数会得到不同的误差值
lasso.fit(x_train,y_train)
lasso_predict = lasso.predict(x_test)
lasso_error = mean_squared_error(y_true=y_test, y_pred=ss_y.inverse_transform(lasso_predict))
print(lasso_error)
print(lasso.alpha_)# 打印出最优alpha值
